package com.mapforge.map;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author Will Morrison
 * 
 */
public class Tile {
	/**
	 * Holds whether this tile is passable in 8 directions declared in the
	 * Direction enumerated type.
	 */
	private List<Boolean> passable;

	/**
	 * The index this tile maps to in its tileset.
	 */
	private int imageIndex;

	/**
	 * The image that represents this tile. May differ from the tile's original
	 * image.
	 */
	private BufferedImage image;

	private Tileset tileset;

	/**
	 * 
	 * @param image
	 */
	public Tile(BufferedImage image, Tileset tileset, int imageIndex) {
		this.imageIndex = imageIndex;
		this.image = image;
		this.tileset = tileset;
		this.passable = new ArrayList<Boolean>(8);
		for (int i = 0; i < passable.size(); i++)
			this.passable.add(true);
	}

	/**
	 * Returns the image index this tile maps to in its tileset.
	 * 
	 * @return
	 */
	public int getIndex() {
		return this.imageIndex;
	}

	/**
	 * Returns the {@link Tileset} this {@link Tile} is a part of.
	 * 
	 * @return this {@link Tile tile's} {@link Tileset tileset.}
	 */
	public Tileset getTileset() {
		return this.tileset;
	}

	/**
	 * This method returns true if this tile is passable in a specific
	 * direction.
	 * 
	 * @param specified
	 *            direction to test if is passable
	 * @return whether this tile is passable from the specified direction
	 */
	public boolean isPassable(Direction direction) {
		int index = -1;
		switch (direction) {
		case UP:
			index = 0;
			break;
		case UP_RIGHT:
			index = 1;
			break;
		case RIGHT:
			index = 2;
			break;
		case DOWN_RIGHT:
			index = 3;
			break;
		case DOWN:
			index = 4;
			break;
		case DOWN_LEFT:
			index = 5;
			break;
		case LEFT:
			index = 6;
			break;
		case UP_LEFT:
			index = 7;
			break;
		}
		return this.passable.get(index);
	}

	public void render(Graphics2D g, int x, int y) {
		g.drawImage(image, x, y, null);
	}

	/**
	 * Tiles are considered equal if they have the same image index.
	 */
	public boolean equals(Object obj) {
		if (obj instanceof Tile) {
			Tile t = (Tile) obj;
			return t.imageIndex == this.imageIndex
					&& t.tileset.equals(this.tileset);
		} else {
			return false;
		}
	}

	public String toString() {
		return "Tile[" + imageIndex + "]";
	}
}
